using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class Lesson10 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        #region 知识点一 回顾客户端需要做的事情
        //1.创建套接字Socket
        //2.用Connect方法连接服务器
        //3.用Send和Receive方法收发数据
        //4.用shutdown和Close方法关闭套接字
        #endregion

        #region 知识点二 实现客户端基本逻辑
        //1.创建套接字Socket
        Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //2.用Connect方法连接服务器
        IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25565);
        try
        {
            socketClient.Connect(ipPoint);
        }
        catch (SocketException e)
        {
            if (e.ErrorCode == 10061)
            {
                print("服务器拒绝连接");
            }
            else
            {
                print("连接服务器失败" + e.ErrorCode);
            }
        }
        #endregion
        //3.用Send和Receive方法收发数据

        //发送数据
        string sendData = "hello,I'm client";
        socketClient.Send(Encoding.UTF8.GetBytes(sendData));

        //这里的接受数据，是阻塞的，即会等待数据返回
        //接受数据
        byte[] receiveData = new byte[1024];
        int receiveNum = socketClient.Receive(receiveData);
        print("接受数据：" + Encoding.UTF8.GetString(receiveData, 0, receiveNum));

        byte[] receiveData2 = new byte[1024];
        int receiveNum2 = socketClient.Receive(receiveData2);
        print("接受数据：" + Encoding.UTF8.GetString(receiveData2, 0, receiveNum2));

        //4.关闭连接
        socketClient.Shutdown(SocketShutdown.Both);
        socketClient.Close();

        #region 总结

        #endregion
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
